<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\model\user;

use app\api\service\User as UserService;
use app\common\model\user\SendMessage as SendMessageModel;
use \app\common\model\WxnoticeTemplate as WxnoticeTemplateModel;
use app\common\model\UserOauth as UserOauthModel;

/**
 * 用户微信消息订阅
 * Class SendMessage
 * @package app\api\model\user
 */
class SendMessage extends SendMessageModel{
    //获取用户是否订阅信息
    public function getUserSubscription(array $type = []){
        $userId      = UserService::getCurrentLoginUserId();
        $wx_template = WxnoticeTemplateModel::wxMessageTemplate($type);
        if (empty($userId) || empty($wx_template)) {
            $this->error = '数据异常';
            return false;
        }
        $list =  (new static)->where(['user_id' => $userId])->where('type', 'in', $type)->select()->toArray();
        $list = array_column($list,null,'type');
        foreach ($wx_template as $key=>$value ){
            $wx_template[$key]['times'] = $list[$key]['times'] ?? 0;
        }
        return $wx_template;
    }
    //订阅数据上报
    public function updateMessageSubscription($type, $times=1){
        $reported_type = ['new_arrival'];//目前只需要上报新品订阅
        $type = array_intersect($type, $reported_type);
        if (empty($type)) {
            $this->error = '订阅无需上报';
            return false;
        }
        $userId      = UserService::getCurrentLoginUserId();
        $wx_template = WxnoticeTemplateModel::wxMessageTemplate($type);
        if (empty($userId) && empty($wx_template)) {
            $this->error = '数据异常';
            return false;
        }

        return (new static)->transaction(function () use ($wx_template,$userId,$times) {
            $data = [];
            foreach ($wx_template as $key=>$value){
                $data['times'] = $times;
                $data['update_time'] = time();
                $exists = (new static)->where(['user_id' => $userId, 'type' => $value['type']])->find();
                if ($exists) {
                    (new static)->where(['user_id' => $userId, 'type' => $value['type']])->inc('times', 1)->update(['update_time'=>time()]);
                } else {
                    $data['oauth_id']  = UserOauthModel::getMpWeiXinOpenId($userId);
                    $data['user_id'] = $userId;
                    $data['type'] = $value['type'];
                    SendMessageModel::add($data);
                }
            }
            return true;
        });
    }
    //用户取消了消息订阅,累计订阅次数清0
    public function userCancelSubscription($template){
        $userId      = UserService::getCurrentLoginUserId();
        if($template == 'all'){//用户关闭了取消订阅的总开关
            return (new static)->where(['user_id' => $userId])->update(['update_time'=>time(),'times'=>0]);
        }
        if(!is_array($template) || empty($template)){
            return false;
        }
        $wx_template = WxnoticeTemplateModel::getSubscriptionTypeByTemplate($template);
        if(empty($wx_template)){
            return false;
        }
        $type = array_values(array_column($wx_template,'type'));
        return (new static)->where(['user_id' => $userId])->where('type', 'in', $type)->update(['update_time'=>time(),'times'=>0]);
    }
}